<template>
  <a-drawer
    :visible="visible"
    :title="title"
    placement="right"
    @close="btnCancel"
    :width="$store.getters.isMobile ? 300 : 370"
    :keyboard="false"
  >
    <a-form
      ref="formRef"
      layout="vertical"
      :model="formState"
      :rules="rules"
      @finish="handleOk"
    >
      <a-form-item label="姓名" name="name">
        <a-input v-model:value="formState.name" placeholder="请填写" />
      </a-form-item>
      <a-form-item label="电话" name="phone">
        <a-input
          type="tel"
          v-model:value="formState.phone"
          placeholder="请填写"
        />
      </a-form-item>
      <a-form-item label="所属公司" name="owner_id">
        <a-auto-complete
          v-model:value="formState.owner_id"
          :options="optionsSeach"
          placeholder="请填写"
          @search="onSearch"
          @select="
            (value, option) => handleAutoCompleteChange('owner_id', option)
          "
        />
      </a-form-item>
      <a-form-item label="通讯地址" name="address">
        <a-input v-model:value="formState.address" placeholder="请填写" />
      </a-form-item>
      <a-form-item label="邮箱" name="email">
        <a-input
          type="email"
          v-model:value="formState.email"
          placeholder="请填写"
        />
      </a-form-item>
      <a-form-item label="是否默认联系人" name="is_default">
        <a-select
          placeholder="请选择是否默认联系人"
          :disabled="disableds"
          v-model:value="formState.is_default"
          :options="selectOptions"
          @select="(value, option) => is_defaultChange('is_default', option)"
        >
        </a-select>
      </a-form-item>
      <div class="drawer-footer">
        <a-button @click.prevent="btnCancels">取消</a-button>
        <a-button class="clear" type="primary" html-type="submit"
          >保存</a-button
        >
      </div>
    </a-form>
  </a-drawer>
</template>

<script>
import { defineComponent, ref, toRaw, reactive, computed, watch } from "vue";
import request from "../../../../common/utils/request";
import { message } from "ant-design-vue";
import BLCOMMON from "bl-common-vue3";

export default defineComponent({
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    id: {
      type: [String, Number],
      default: 0,
    },
  },
  setup(props, context) {
    const selectOptions = ref([
      {
        value: "1",
        label: "是",
      },
      {
        value: "0",
        label: "否",
      },
    ]);
    const disableds = ref(false);
    const filterOption = (input, option) => {
      return option.value.toLowerCase().indexOf(input.toLowerCase()) >= 0;
    };

    let is_defaultState = {};
    const is_defaultChange = (key, option) => {
      is_defaultState[key] = option.value;
    };

    //   表单
    const formState = reactive({
      name: "",
      phone: null,
      email: null,
      address: "",
      is_default: undefined,
      owner_id: "",
    });
    //
    //表单验证
    const formRef = ref();
    const rules = {
      name: [
        {
          required: true,
          message: `请输入${BLCOMMON.utils.L("租客")}姓名`,
          trigger: "blur",
        },
      ],
      phone: [
        {
          message: "请输入电话",
          trigger: "blur",
          required: true,
        },
      ],
      is_default: [
        {
          message: "请选择是否为默认联系人",
          trigger: "change",
          required: true,
        },
      ],
    };
    // 保存新建下一个
    const btnCancels = () => {
      btnCancel();
    };
    //   关闭弹窗
    const btnCancel = () => {
      context.emit("btnCancel");
      formRef.value.resetFields();
    };
    //

    // 确定
    const handleOk = () => {
      let params = JSON.parse(JSON.stringify(formState));
      for (let key in autoFillState) {
        params[key] = autoFillState[key];
      }
      for (let key in is_defaultState) {
        params[key] = is_defaultState[key];
      }
      params.needMsg = true;
      let requestMethod = "post";
      if (props.id) {
        requestMethod = "put";
      }
      request[requestMethod]("/org", "/owner/ownerContacts", params).then(
        (res) => {
          context.emit("ok");
          message.success(res.msg || "操作成功！");
          formRef.value.resetFields();
        }
      );
    };

    // 搜索处理
    let autoFillState = {};
    const handleAutoCompleteChange = (key, option) => {
      autoFillState[key] = option.id;
    };
    // 搜索serach
    const optionsSeach = ref([]);
    const onSearch = (searchText) => {
      if (!searchText) {
        optionsSeach.value = [];
      } else {
        searchList();
      }
    };
    const searchList = () => {
      request.get("/org", "/owner/manage").then((res) => {
        optionsSeach.value = res.list.map((item) => ({
          value: item.name,
          label: item.name,
          id: item.id,
        }));
      });
    };
    // 搜索节流
    // let timeout = null;
    // let currentValue = "";
    // const getResult = (value, callback) => {
    //   if (timeout) {
    //     clearTimeout(timeout);
    //     timeout = null;
    //   }
    //   currentValue = value;
    //   // 搜素请求
    //   const searchList = () => {
    //     request.get("/org", "/owner/manage").then((res) => {
    //       console.log(res);
    //       if (currentValue === value) {
    //         let result = [];
    //         if (res.list) {
    //           result = res.list.map((item) => ({
    //             value: item.name,
    //             label: item.name,
    //           }));
    //         }
    //         callback(result);
    //       }
    //     });
    //   };
    //   timeout = setTimeout(searchList, 3000);
    // };
    //  编辑详情
    let detail = {};
    // 编辑详情
    const getBuildingDetail = () => {
      request
        .get("/org", "/owner/ownerContacts/detail", { id: props.id })
        .then((res) => {
          detail = res.detail;
          setModelRef(detail);
          autoFillState.owner_id = detail.owner_id;
          is_defaultState.is_default = detail.is_default;
          formState.is_default = detail.is_default == 0 ? "否" : "是";
          formState.owner_id = detail.owner_name;
        });
    };
    const setModelRef = (state) => {
      for (let key in state) {
        formState[key] = state[key];
      }
    };
    const title = computed(() => {
      return props.id
        ? `编辑${BLCOMMON.utils.L("租客")}联系人`
        : `新建${BLCOMMON.utils.L("租客")}联系人`;
    });
    watch(
      () => props.visible,
      (val) => {
        if (val) {
          if (props.id) {
            getBuildingDetail();
          } else {
            formState.owner_id = "";
          }
        }
      }
    );
    return {
      is_defaultChange,
      filterOption,
      handleOk,
      btnCancel,
      formState,
      disableds,
      selectOptions,
      rules,
      formRef,
      btnCancels,
      title,
      onSearch,
      optionsSeach,
      handleAutoCompleteChange,
    };
  },
});
</script>

<style lang="less" scoped>
.clear {
  margin-left: 10px;
}
</style>
